<template>
  <div class="login">
    <div class="login_box">
      <div class="box_logo">
        <img src="@/assets/logo.png" alt="">
      </div>
      <!-- form表单 -->
      <el-form :model="ruleForm" :rules="rules" ref="reform" class="form_conent">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user-solid" type="text" v-model="ruleForm.username" placeholder="请输入用户名">
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-warning" type="text" v-model="ruleForm.password" placeholder="请输入密码">
          </el-input>
        </el-form-item>
        <el-form-item class="button">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button @click="out">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
  data() {
    return {
      ruleForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    ...mapMutations(['getToken']),
    login() {
      this.$refs.reform.validate(async (valid) => {
        if (valid) {
          this.$message.success('表单校验通过');
          /* 向后端发送登录请求 */
          let res = await this.$http.post('login', this.ruleForm);
          // console.log(res);
          if (res.meta.status == 200) {
            /* 后台返回token保存到vuex */
            // console.log( res.data.token);
            this.getToken({token:res.data.token});
            this.$message.success(res.meta.msg);
            this.$router.push('/');
          } else {
            this.$message.error(res.meta.msg);
          }
        } else {
          this.$message.error('表单校验未通过')
        }
      });
    },
    out() {
      this.$refs.reform.resetFields();
    }
  }
}
</script>

<style lang="scss">
.login {
  width: 100%;
  height: 100%;
  background-color: #2b4b6b;
  min-width: 720px;
  position: relative;

  .login_box {
    width: 450px;
    height: 300px;
    background-color: white;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    .box_logo {
      width: 150px;
      height: 150px;
      background-color: #ccc;
      border: 14px solid white;
      box-shadow: 0 0 10px black;
      border-radius: 50%;
      position: absolute;
      left: 50%;
      transform: translate(-50%, -50%);

      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;

      }
    }

    .form_conent {
      width: 100%;
      margin-top: 100px;
      padding: 0 10px;

      .button {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}
</style>